<?php 
include("timefunc.php");
date_default_timezone_set('Asia/Bangkok'); 
function dbconfig(){
	//$con = mysql_connect("localhost","root","");
	$con = mysql_connect("localhost","phamios_adstore","3xV}f=^6AWn8");
	return $con;
}
function dbconnection($con){ 
	if (!$con)
	  {
	  	return false;
	  }else{
	  	mysql_select_db("store8x", $con); 
	  	mysql_select_db("phamios_store8x", $con); 
	  	return true;
	  } 
}

function addmo($commandcode,$serviceid,$userid,$message,$requestid){
	 if(dbconnection(dbconfig()) == false){
	 	return false;
	 }else{
	 	 date_default_timezone_set('Asia/Bangkok'); 
		 $timenow = time();
		 $today = date('d-m-Y');
		 $intime = date('h:i:s A');
		 $query2= "INSERT INTO tbmos(dest, phone, content,created,telco,cmdcode,requestId,today,timenow) VALUES('".$serviceid."','".$userid."','".$message."','".$timenow."','".null."','".$commandcode."','".$requestid."','".$today."','".$intime."')";
		  if (!mysql_query($query2,dbconfig()))
		  {
		  	 closeconnect(dbconfig());
		  	 return false;
		  }else{
		  	closeconnect(dbconfig());
			return true;
		  }
	 }
}
function closeconnect($con){
	 mysql_close($con);
}
function checkrequestid($requestid){
	dbconnection(dbconfig());
	$sql = "SELECT COUNT(*) AS total FROM tbmos WHERE requestId ='".$requestid."'";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	$total = $row['total'];
	closeconnect(dbconfig());
	return $total;
}

function check_phone_time($phone){
	dbconnection(dbconfig());
	date_default_timezone_set('Asia/Bangkok'); 
	$today = date('d-m-Y');
	$intime = date('h:i:s A');
	$sql = "SELECT id,timenow FROM tbmos WHERE today ='".$today."' AND phone='".$phone."' order by id desc";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	$total = $row['timenow'];
	closeconnect(dbconfig());
	if($total > 1){
		date_default_timezone_set('Asia/Bangkok'); 
		$now = strtotime(date('h:i:s A'));
		$last= strtotime($total); 
		$time_elapsed = $now - $last; 
		if($time_elapsed > 60 ){
			return true;
		}else{
			return false;
		}
	}else{
		return true;
	}
	
}

function getlastphoneidtoday($phone){
	dbconnection(dbconfig());
	date_default_timezone_set('Asia/Bangkok'); 
	$today = date('d-m-Y');
	$sql = "SELECT id FROM tbmos WHERE today ='".$today."' AND phone='".$phone."' order by id";
	$query = mysql_query($sql); 
	$total = null;
	$id = null;
	while($row = mysql_fetch_array($query))
	  { 
	 	$id = $row['id'];
	  }
	closeconnect(dbconfig());
	return $id;
}


function checkphonetoday($phone){
	dbconnection(dbconfig());
	$today = date('d-m-Y');
	$intime = date('h:i:s');  
	$sql = "SELECT count(*) AS total FROM tbmos WHERE today ='".$today."' AND phone='".$phone."'";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	$total = $row['total'];
	closeconnect(dbconfig());
	if($total < 10 ){
		return true;
	}else{
		return false;
	}
}

?>